package org.mtmi.ui.scenes.actions;

import java.util.ArrayList;

import org.eclipse.swt.graphics.Point;
import org.mtmi.ui.M;
import org.mtmi.ui.actions.Action;
import org.mtmi.ui.actions.IRetargetableAction;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.listeners.PopupListener;
import org.mtmi.ui.controls.popups.AbstractButtonPopup;
import org.mtmi.ui.controls.popups.AddControlPopup;
import org.mtmi.ui.drawables.IDrawable;
import org.mtmi.ui.drawables.SymbolDrawable;
import org.mtmi.ui.scenes.COLOR;
import org.mtmi.ui.scenes.Scene;
import org.mtmi.ui.scenes.SceneManager;

/**
 * Add control to current scene.
 */
public class AddControlAction extends Action
{
	private SymbolDrawable image;
	
	public AddControlAction() {
		super( PUSH );
	}
	
	@Override
	public String getText() {
		return "Add Control";
	}
	
	@Override
	public IDrawable getImage() {
		if( image==null ) {
			image = new SymbolDrawable( COLOR.green, SymbolDrawable.PLUS );
		}
		return image;
	}
	
	@Override
	public boolean isEnabled() {
		return true;
	}
	
	@Override
	public void run() {
		final Scene scene = SceneManager.getDefault().getScene();
		final AddControlPopup p = new AddControlPopup( scene, M.SCENE_EDITOR_CONTROL );
		p.addResponseListener( new PopupListener() {
			@Override
			public void popupButtonSelected( int id ) {
				if( id == AbstractButtonPopup.OK ) {
					IRetargetableAction creator = p.getSelectedAction();
					creator.setTarget( scene );
					creator.run();
					Control n =  (Control)creator.getTarget();
					Point s = n.getSize();
					Point sz = scene.getSize();
					n.setLocation( (sz.x-s.x)/2, (sz.y-s.y)/2 );
					ArrayList<Control> sel = new ArrayList<Control>();
					sel.add( n );
					scene.setSelection( sel );
					scene.redraw();
				}
			}
		});
	}
}
